package com.superdaxue.rxsampledemo.model;

import android.util.Log;

import com.superdaxue.rxsampledemo.bean.DataBean;
import com.superdaxue.rxsampledemo.configs.AppConfigs;
import com.superdaxue.rxsampledemo.retrofitservice.RetrofitService;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ZX_CC on 2016/5/24.
 */
public class ShowContentModel implements ShowContentBiz {
    private  Subscription sub;
    private boolean state = false;
    public boolean isState() {
        return state;
    }

    @Override
    public void onResult(final onShowContentListener onShowContentListener ,int p) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppConfigs.URL_DATA)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        RetrofitService retrofitService = retrofit.create(RetrofitService.class);

        Map<String,String> map  = new HashMap<>();
        map.put(AppConfigs.APPID_NAME,AppConfigs.APPID);
        map.put(AppConfigs.SECRECT_NAME,AppConfigs.SECRECT);
        map.put(AppConfigs.PAGE_NAME,""+p);
        map.put(AppConfigs.NUM_NAME,AppConfigs.NUM);
        state = true;//设置为正在请求数据

        sub = retrofitService.getDataBean(map)
                 .subscribeOn(Schedulers.io())
                 .observeOn(AndroidSchedulers.mainThread())
                 .subscribe(new Subscriber<DataBean>() {
                           @Override
                           public void onCompleted() {
                               state = false;
                           }

                           @Override
                           public void onError(Throwable e) {
                                state = false;
                                onShowContentListener.onFailed(e.getMessage());
                           }

                           @Override
                           public void onNext(DataBean dataBean) {
                               if (dataBean != null)
                                   onShowContentListener.onSuccess(dataBean);
                           }
                 });
    }

    public void cancelRequest(){
         if ( sub != null && !sub.isUnsubscribed()){
               sub.unsubscribe();
         }
    }
}
